﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using Lua;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Loaders;
using UnityEngine;

// Token: 0x02000304 RID: 772
public class LuaManager : MonoBehaviour
{
	// Token: 0x06001388 RID: 5000 RVA: 0x00082C4C File Offset: 0x00080E4C
	private void IntializeValues()
	{
		UnityEngine.Transform target = Camera.main.GetComponent<PlayerCamera>().target;
		Player component = target.GetComponent<Player>();
		this.p_player = new PlayerEntity(component);
		this.world = new World();
		this.gts = new AllGiantess();
		this.micros = new AllMicros();
		this.globalTable = new Globals();
		this.resourceSettings = new XmlResourceSettingReader(true);
	}

	// Token: 0x06001389 RID: 5001 RVA: 0x00082CB4 File Offset: 0x00080EB4
	private void Start()
	{
		UserData.RegisterAssembly(null, false);
		this.IntializeValues();
		this.LoadBehaviors();
		this.LuaInitialize();
		this.LuaStart();
	}

	// Token: 0x0600138A RID: 5002 RVA: 0x00082CD5 File Offset: 0x00080ED5
	private void Update()
	{
		this.LuaUpdate();
	}

	// Token: 0x0600138B RID: 5003 RVA: 0x00082CDD File Offset: 0x00080EDD
	public void UpdatePlayer(Player player)
	{
		this.p_player = new PlayerEntity(player);
		this.UpdatePlayerReference();
	}

	// Token: 0x0600138C RID: 5004 RVA: 0x00082CF4 File Offset: 0x00080EF4
	private string[] GetAllLuaFiles()
	{
		List<string> list = new List<string>();
		List<string> list2 = new List<string>();
		list2.Add(Application.streamingAssetsPath + "/lua/behaviors/");
		list2.AddRange(this.resourceSettings.LuaPaths);
		foreach (string text in list2)
		{
			if (Directory.Exists(text))
			{
				list.AddRange(Directory.GetFiles(text));
			}
			else
			{
				Debug.Log("Could not find lua script folder: " + text);
			}
		}
		return list.ToArray();
	}

	// Token: 0x0600138D RID: 5005 RVA: 0x00082DA8 File Offset: 0x00080FA8
	private void LoadBehaviors()
	{
		BehaviorLists.Initialize();
		string[] allLuaFiles = this.GetAllLuaFiles();
		foreach (string text in allLuaFiles)
		{
			if (text.EndsWith(".lua"))
			{
				string fileName = Path.GetFileName(text);
				string code = File.ReadAllText(text);
				Script script = this.InitializeScript();
				try
				{
					script.DoString(code, null, fileName);
					try
					{
						Table table = script.Globals.Get("behaviorList").Table;
						foreach (TablePair tablePair in table.Pairs)
						{
							try
							{
								LuaBehavior luaBehavior = new LuaBehavior(tablePair.Value.Table, script);
								luaBehavior.filename = fileName;
								BehaviorLists.Instance.AddBehavior(luaBehavior);
							}
							catch (Exception ex)
							{
								Debug.LogError("Error loading script: " + fileName);
								Debug.LogError(ex.Message);
								Debug.LogError(ex.StackTrace);
							}
						}
					}
					catch (ScriptRuntimeException ex2)
					{
						Debug.LogError(ex2.DecoratedMessage);
					}
				}
				catch (ScriptRuntimeException ex3)
				{
					Debug.LogError(ex3.DecoratedMessage);
				}
				catch (SyntaxErrorException ex4)
				{
					Debug.LogError(ex4.DecoratedMessage);
				}
			}
		}
	}

	// Token: 0x0600138E RID: 5006 RVA: 0x00082F4C File Offset: 0x0008114C
	private void LoadMotives()
	{
		string path = Application.streamingAssetsPath + "/lua/motives/";
		string[] files = Directory.GetFiles(path);
		foreach (string text in files)
		{
			if (text.EndsWith(".lua"))
			{
				string fileName = Path.GetFileName(text);
				string code = File.ReadAllText(text);
				Script script = this.InitializeScript();
				try
				{
					script.DoString(code, null, null);
					try
					{
						Table table = script.Globals.Get("motiveList").Table;
						foreach (TablePair tablePair in table.Pairs)
						{
							try
							{
								LuaMotive luaMotive = new LuaMotive(tablePair.Value.Table, script);
								luaMotive.filename = fileName;
								BehaviorLists.Instance.AddMotive(luaMotive);
							}
							catch (Exception ex)
							{
								Debug.LogError("Error loading script: " + fileName);
								Debug.LogError(ex.Message);
								Debug.LogError(ex.StackTrace);
							}
						}
					}
					catch (ScriptRuntimeException ex2)
					{
						Debug.LogError(ex2.DecoratedMessage);
					}
				}
				catch (ScriptRuntimeException ex3)
				{
					Debug.LogError(ex3.DecoratedMessage);
				}
				catch (SyntaxErrorException ex4)
				{
					Debug.LogError(ex4.DecoratedMessage);
				}
			}
		}
	}

	// Token: 0x0600138F RID: 5007 RVA: 0x00083100 File Offset: 0x00081300
	private void LuaInitialize()
	{
		List<string[]> list = this.LoadScripts();
		this.luaScripts = new List<LuaManager.LuaScript>();
		foreach (string[] array in list)
		{
			LuaManager.LuaScript luaScript = new LuaManager.LuaScript();
			luaScript.script = this.InitializeScript();
			try
			{
				luaScript.script.DoString(array[1], null, array[0]);
			}
			catch (ScriptRuntimeException ex)
			{
				Debug.LogError(ex.DecoratedMessage);
			}
			luaScript.start = luaScript.script.Globals.Get("Start");
			if (luaScript.start == DynValue.Nil)
			{
				luaScript.start = null;
			}
			luaScript.update = luaScript.script.Globals.Get("Update");
			if (luaScript.update == DynValue.Nil)
			{
				luaScript.update = null;
			}
			luaScript.coroutine = luaScript.script.Globals.Get("Coroutine");
			if (luaScript.coroutine == DynValue.Nil)
			{
				luaScript.coroutine = null;
			}
			else
			{
				DynValue function = luaScript.script.Globals.Get("Coroutine");
				luaScript.coroutine = luaScript.script.CreateCoroutine(function);
			}
			this.luaScripts.Add(luaScript);
		}
	}

	// Token: 0x06001390 RID: 5008 RVA: 0x00083294 File Offset: 0x00081494
	private void LuaStart()
	{
		foreach (LuaManager.LuaScript luaScript in this.luaScripts)
		{
			if (luaScript.start != null)
			{
				luaScript.script.Call(luaScript.start);
			}
		}
	}

	// Token: 0x06001391 RID: 5009 RVA: 0x00083308 File Offset: 0x00081508
	private void LuaUpdate()
	{
		if (this.luaScripts == null)
		{
			if (!this.updateErrorPrinted)
			{
				Debug.LogError("No script could be loaded due to error in one of them");
				this.updateErrorPrinted = true;
			}
			return;
		}
		foreach (LuaManager.LuaScript luaScript in this.luaScripts)
		{
			if (luaScript.update != null)
			{
				try
				{
					luaScript.script.Call(luaScript.update);
				}
				catch (ScriptRuntimeException ex)
				{
					Debug.Log(ex.DecoratedMessage);
				}
			}
			if (luaScript.coroutine != null)
			{
				luaScript.coroutine.Coroutine.Resume();
			}
		}
	}

	// Token: 0x06001392 RID: 5010 RVA: 0x000833E0 File Offset: 0x000815E0
	private List<string[]> LoadScripts()
	{
		string path = Application.streamingAssetsPath + "/lua/";
		string[] files = Directory.GetFiles(path);
		List<string[]> list = new List<string[]>();
		foreach (string text in files)
		{
			if (text.EndsWith(".lua"))
			{
				string fileName = Path.GetFileName(text);
				string text2 = LuaManager.LoadLuaFile(text);
				list.Add(new string[]
				{
					fileName,
					text2
				});
			}
		}
		return list;
	}

	// Token: 0x06001393 RID: 5011 RVA: 0x00083468 File Offset: 0x00081668
	private void UpdatePlayerReference()
	{
		foreach (LuaManager.LuaScript luaScript in this.luaScripts)
		{
			luaScript.script.Globals["player"] = this.p_player;
		}
	}

	// Token: 0x06001394 RID: 5012 RVA: 0x000834D8 File Offset: 0x000816D8
	public static string LoadLuaFile(string path)
	{
		return File.ReadAllText(path);
	}

	// Token: 0x06001395 RID: 5013 RVA: 0x000195B1 File Offset: 0x000177B1
	private static void Log(string message)
	{
		Debug.Log(message);
	}

	// Token: 0x06001396 RID: 5014 RVA: 0x000834E0 File Offset: 0x000816E0
	public Script InitializeScript()
	{
		Script script = new Script();
		Table globals = script.Globals;
		object key = "Log";
		if (LuaManager.<>f__mg$cache0 == null)
		{
			LuaManager.<>f__mg$cache0 = new Action<string>(LuaManager.Log);
		}
		globals[key] = LuaManager.<>f__mg$cache0;
		Table globals2 = script.Globals;
		object key2 = "log";
		if (LuaManager.<>f__mg$cache1 == null)
		{
			LuaManager.<>f__mg$cache1 = new Action<string>(LuaManager.Log);
		}
		globals2[key2] = LuaManager.<>f__mg$cache1;
		script.Globals["player"] = this.p_player;
		script.Globals["world"] = this.world;
		script.Globals["gts"] = this.gts;
		script.Globals["micros"] = this.micros;
		script.Globals["globals"] = this.globalTable;
		script.Globals["Animation"] = typeof(Lua.Animation);
		script.Globals["AudioSource"] = typeof(Lua.AudioSource);
		script.Globals["Entity"] = typeof(Entity);
		script.Globals["Event"] = typeof(Lua.Event);
		script.Globals["EventCode"] = typeof(EventCode);
		script.Globals["Input"] = typeof(Lua.Input);
		script.Globals["Mathf"] = typeof(Lua.Mathf);
		script.Globals["Quaternion"] = typeof(Lua.Quaternion);
		script.Globals["Random"] = typeof(Lua.Random);
		script.Globals["Screen"] = typeof(Lua.Screen);
		script.Globals["CustomSoundManager"] = typeof(CustomSoundManager);
		script.Globals["Time"] = typeof(Lua.Time);
		script.Globals["Vector3"] = typeof(Lua.Vector3);
		ScriptOptions options = script.Options;
		if (LuaManager.<>f__mg$cache2 == null)
		{
			LuaManager.<>f__mg$cache2 = new Action<string>(LuaManager.Log);
		}
		options.DebugPrint = LuaManager.<>f__mg$cache2;
		script.Options.ScriptLoader = new LuaManager.StreamingAssetsScriptLoader();
		script.DoString(LuaManager.initializationCode, null, null);
		return script;
	}

	// Token: 0x040016DD RID: 5853
	private List<LuaManager.LuaScript> luaScripts;

	// Token: 0x040016DE RID: 5854
	private PlayerEntity p_player;

	// Token: 0x040016DF RID: 5855
	private World world;

	// Token: 0x040016E0 RID: 5856
	private AllGiantess gts;

	// Token: 0x040016E1 RID: 5857
	private AllMicros micros;

	// Token: 0x040016E2 RID: 5858
	private Globals globalTable;

	// Token: 0x040016E3 RID: 5859
	private bool updateErrorPrinted;

	// Token: 0x040016E4 RID: 5860
	private XmlResourceSettingReader resourceSettings;

	// Token: 0x040016E5 RID: 5861
	private static string initializationCode = "\r\n\t-- BEHAVIOR\r\n\tBehaviorBase = { agent = nil }\r\n\tbehaviorList = {}\r\n\r\n\tfunction BehaviorBase:new(o)\r\n\t\to = o or {}\r\n\t\tsetmetatable(o, self)\r\n\t\tself.__index = self\r\n\t\treturn o\r\n\tend\r\n\r\n\tfunction RegisterBehavior(behaviorName) \r\n\t\tlocal b = BehaviorBase:new{name = behaviorName}\r\n\t\tbehaviorList[behaviorName] = b\r\n\t\treturn b\r\n\tend\r\n\r\n\tfunction CreateInstance(behaviorName, newagent, target, cursor)\r\n\t\tlocal BehaviorClass = behaviorList[behaviorName]\r\n\t\tlocal instance = BehaviorClass:new{name = behaviorName, agent = newagent, target = target, cursorPoint = cursor}\r\n\t\treturn instance\r\n\tend\r\n\r\n\t-- MOTIVE\r\n\r\n\tMotiveBase = { agent = nil }\r\n\tmotiveList = {}\r\n\r\n\tfunction MotiveBase:new(o)\r\n\t\to = o or {}\r\n\t\tsetmetatable(o, self)\r\n\t\tself.__index = self\r\n\t\treturn o\r\n\tend\r\n\r\n\tfunction RegisterMotive(motiveName) \r\n\t\tlocal b = MotiveBase:new{name = motiveName}\r\n\t\tmotiveList[motiveName] = b\r\n\t\treturn b\r\n\tend\r\n\r\n\tfunction CreateMotiveInstance(motiveName, newagent)\r\n\t\tlocal MotiveClass = motiveList[motiveName]\r\n\t\tlocal instance = MotiveClass:new{name = motiveName, agent = newagent}\r\n\t\treturn instance\r\n\tend\r\n\r\n\r\n\t\r\n\t";

	// Token: 0x040016E6 RID: 5862
	[CompilerGenerated]
	private static Action<string> <>f__mg$cache0;

	// Token: 0x040016E7 RID: 5863
	[CompilerGenerated]
	private static Action<string> <>f__mg$cache1;

	// Token: 0x040016E8 RID: 5864
	[CompilerGenerated]
	private static Action<string> <>f__mg$cache2;

	// Token: 0x02000305 RID: 773
	public class LuaScript
	{
		// Token: 0x06001398 RID: 5016 RVA: 0x00083760 File Offset: 0x00081960
		public LuaScript()
		{
			this.script = new Script();
		}

		// Token: 0x040016E9 RID: 5865
		public Script script;

		// Token: 0x040016EA RID: 5866
		public DynValue start;

		// Token: 0x040016EB RID: 5867
		public DynValue update;

		// Token: 0x040016EC RID: 5868
		public DynValue coroutine;
	}

	// Token: 0x02000306 RID: 774
	private class StreamingAssetsScriptLoader : ScriptLoaderBase
	{
		// Token: 0x06001399 RID: 5017 RVA: 0x00083773 File Offset: 0x00081973
		internal StreamingAssetsScriptLoader()
		{
			base.ModulePaths = new string[]
			{
				"?.lua",
				"behaviors/?.lua"
			};
		}

		// Token: 0x0600139A RID: 5018 RVA: 0x00083798 File Offset: 0x00081998
		public override object LoadFile(string file, Table globalContext)
		{
			string path = Application.streamingAssetsPath + "/lua/" + file;
			if (!File.Exists(path))
			{
				Debug.LogError(file + " could not be found in lua directory");
				return null;
			}
			return LuaManager.LoadLuaFile(path);
		}

		// Token: 0x0600139B RID: 5019 RVA: 0x000837D9 File Offset: 0x000819D9
		public override bool ScriptFileExists(string name)
		{
			return File.Exists(Application.streamingAssetsPath + "/lua/" + name);
		}
	}
}
